package com.test.design.example1.factorymethod;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.VolatileImage;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountdownTimer {
    public static Double time = 63.0 * 60;
    public static Long startTime =  System.currentTimeMillis();
    public static void main(String[] args) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 定义时间格式
        String timeLeft = format.format(new Date());// 倒计时60秒

        LocalDateTime now = LocalDateTime.now();
        String s = now.toString();
        String[] ts = s.split("T");

        // 创建弹窗
        JFrame frame = new JFrame("倒计时");
        JLabel label = new JLabel("总计时间" + Math.round(time) + "秒", SwingConstants.CENTER);
//        JLabel label = new JLabel("系统当前时间: " + ts[0] + " " + ts[1], SwingConstants.CENTER);
//        JLabel label = new JLabel("系统当前时间: " + timeLeft, SwingConstants.CENTER);
        JButton button = new JButton("关闭");

        // 设置按钮点击事件
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frame.dispose(); // 关闭弹窗
            }
        });

        frame.add(label, "Center");
        frame.add(button, "South");
        frame.setSize(300, 150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        // 创建定时器
        Timer timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                time -= 1;
                System.out.println(time);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 定义时间格式
                String timeLeft = format.format(new Date());// 倒计时60秒

                LocalDateTime now = LocalDateTime.now();
                String s = now.toString();
                String[] ts = s.split("T");
                long nowTime = (System.currentTimeMillis() - startTime) / 1000;

//                label.setText("系统当前时间: " + ts[0] + " " + ts[1]);
//                label.setText("系统当前时间: " + timeLeft);

                label.setText("倒计时剩余: " + Math.round(time) + "秒");
                if (time.equals(10.0) ) {
                    ((Timer) e.getSource()).stop(); // 停止定时器
                    JOptionPane.showMessageDialog(frame, "时间到！", "提示", JOptionPane.INFORMATION_MESSAGE);
                    frame.dispose(); // 关闭弹窗
                }
            }
        });
        timer.start(); // 启动定时器
    }
}